﻿using Model;
using Service.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using Common;

namespace Service
{

    /// <summary>
    /// 命令的分发类
    /// </summary>
    public class CommandDispatcher
    {
        private CommandService CommandService = new CommandServiceImpl();
        /// <summary>
        /// 注册一个命令
        /// </summary>
        public BaseResult<int> RegisterCommand(Command command)
        {
            return CommandService.Save(command);
        }
        /// <summary>
        /// 解析一个要运行的command
        /// </summary>
        public CommandParseResult ParseRunCommand(string command)
        {
            CommandParseResult cpr = CommandService.ParseCommand(command);
            if (cpr.Success)
            {
                //参数设置到context中
                CommonObject.CommandContext.InputCommandParams = cpr.Params;
                CommonObject.CommandContext.Command = cpr.Data.FullCommand;
                //如果service对象已经创建
                var service = ServiceFactory.CreateService(cpr.Data.Type);
                var methodInfo = service.GetType().GetMethod(cpr.Data.Method);
                if (methodInfo != null)
                {
                    var res = methodInfo.Invoke(service, new object[0]);
                    if(res != null)
                    {
                        cpr.Description = res.ToString();
                    }
                }
                else
                {
                    throw new Exception($"类型{cpr.Data.Type}没有方法{cpr.Data.Method}");
                }
            }
            return cpr;
        }
        /// <summary>
        /// 通过主项目中的commands.json注册命令
        /// </summary>
        public void RegisterCommands()
        {
            Assembly asm = Assembly.Load("NetManagerSystem");
            var resources = asm.GetManifestResourceNames();
            //遍历所有json文件
            foreach(string resource in resources)
            {
                if (resource.EndsWith(".json") && resource.StartsWith(asm.GetName().Name + ".Command"))
                {
                    Stream s = asm.GetManifestResourceStream(resource);
                    using (StreamReader sr = new StreamReader(s))
                    {
                        string json = sr.ReadToEnd();
                        Command c = JsonConvert.DeserializeObject<Command>(json);
                        CommandService.Save(c);
                    }
                }
            }
        }
        /// <summary>
        /// 获取下一个输入项
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public CommandNextInputResult ParseNextInputCommand(string command)
        {
            CommandNextInputResult cpr = CommandService.ParseNextInputCommand(command);
            return cpr;
        }
    }
}
